package com.tudouji.project.mt.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.tudouji.common.exception.CustomException;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.project.bill.domain.*;
import com.tudouji.project.bill.mapper.ProducereportMapper;
import com.tudouji.project.bill.mapper.ProducereportitemMapper;
import com.tudouji.project.bill.mapper.WhoutformMapper;
import com.tudouji.project.bill.mapper.WhoutformitemMapper;
import com.tudouji.project.customer.domain.Customer;
import com.tudouji.project.customer.mapper.CustomerMapper;
import com.tudouji.project.mt.domain.*;
import com.tudouji.project.mt.mapper.MtFoodconsumgoodsitemMapper;
import com.tudouji.project.mt.mapper.MtFoodconsumitemMapper;
import com.tudouji.project.mt.mapper.MtShopMapper;
import com.tudouji.project.mt.service.IMtShopService;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.mapper.DepartmentMapper;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.product.domain.Salesspecification;
import com.tudouji.project.purchasebill.domain.Purchasebillitem;
import com.tudouji.project.store.domain.Storehouseroom;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tudouji.project.mt.mapper.MtFoodconsumMapper;
import com.tudouji.project.mt.service.IMtFoodconsumService;

import static com.tudouji.common.utils.DateUtils.YYYYMMDD;

/**
 * 美团菜品消耗单主Service业务层处理
 *
 * @author tudouji
 * @date 2023-11-21
 */
@Service
public class MtFoodconsumServiceImpl implements IMtFoodconsumService {
    @Autowired
    private MtFoodconsumMapper mtFoodconsumMapper;
    @Autowired
    private MtShopMapper mtShopMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private ProducereportMapper producereportMapper;
    @Autowired
    private ProducereportitemMapper producereportitemMapper;
    @Autowired
    private BusinesscodeServiceImpl codeService;
    @Autowired
    private WhoutformMapper whoutformMapper;
    @Autowired
    private WhoutformitemMapper whoutformitemMapper;
    @Autowired
    private IMtShopService mtShopService;

    /**
     * 查询美团菜品消耗单主
     *
     * @param id 美团菜品消耗单主ID
     * @return 美团菜品消耗单主
     */
    @Override
    public MtFoodconsum selectMtFoodconsumById(Long id) {
        return mtFoodconsumMapper.selectMtFoodconsumById(id);
    }

    /**
     * 查询美团菜品消耗单主列表
     *
     * @param mtFoodconsum 美团菜品消耗单主
     * @return 美团菜品消耗单主
     */
    @Override
    public List<MtFoodconsum> selectMtFoodconsumList(MtFoodconsum mtFoodconsum) {
        return mtFoodconsumMapper.selectMtFoodconsumList(mtFoodconsum);
    }

    /**
     * 新增美团菜品消耗单主
     *
     * @param mtFoodconsum 美团菜品消耗单主
     * @return 结果
     */
    @Override
    public int insertMtFoodconsum(MtFoodconsum mtFoodconsum) {
        mtFoodconsum.setCreateTime(DateUtils.getNowDate());
        return mtFoodconsumMapper.insertMtFoodconsum(mtFoodconsum);
    }

    /**
     * 修改美团菜品消耗单主
     *
     * @param mtFoodconsum 美团菜品消耗单主
     * @return 结果
     */
    @Override
    public int updateMtFoodconsum(MtFoodconsum mtFoodconsum) {
        mtFoodconsum.setUpdateTime(DateUtils.getNowDate());
        return mtFoodconsumMapper.updateMtFoodconsum(mtFoodconsum);
    }

    /**
     * 批量删除美团菜品消耗单主
     *
     * @param ids 需要删除的美团菜品消耗单主ID
     * @return 结果
     */
    @Override
    public int deleteMtFoodconsumByIds(Long[] ids) {
        return mtFoodconsumMapper.deleteMtFoodconsumByIds(ids);
    }

    /**
     * 删除美团菜品消耗单主信息
     *
     * @param id 美团菜品消耗单主ID
     * @return 结果
     */
    @Override
    public int deleteMtFoodconsumById(Long id) {
        return mtFoodconsumMapper.deleteMtFoodconsumById(id);
    }

    @Override
    public void dataPush(List<MtShop> mtShopList) {
        for (MtShop shop : mtShopList) {
            int pushDays = shop.getPushDays();
            HashMap<String, Date> PUSH_DATE = mtShopService.getPushDate(shop);
            Date bizTimeLastEnd = PUSH_DATE.get("bizTimeLastEnd");
            Date bizTimeEnd = PUSH_DATE.get("bizTimeEnd");
            Date bizTimeStart = PUSH_DATE.get("bizTimeStart");

            while (0 < DateUtils.getDateDiff(bizTimeLastEnd, bizTimeEnd)) {
                //1、菜品消耗单明细表中的物料数据生成领料出库报表（preduceReport），按日、按门店、按菜品、按物料汇总生成，成本对象记录为菜品的ERP物料id，每个门店每天每个菜品一张领料出库单。
                MtFoodconsum mtFoodconsum = new MtFoodconsum();
                mtFoodconsum.setMtShopld(shop.getId());
                mtFoodconsum.setOrderstarttimegte(bizTimeStart.getTime());
                mtFoodconsum.setOrderendtimelte(bizTimeEnd.getTime());
                mtFoodconsum.setStatus(50);
                List<MtFoodconsumgoodsitem> goodsItems = mtFoodconsumMapper.dataForProduceReport(mtFoodconsum);

                createProduceReport(bizTimeStart, bizTimeEnd, goodsItems);
                //领料出库单
//                createOut(goodsItems);
                //2、	菜品消耗明细表中的菜品数据生成销售出库单，按日、按门店汇总生成，每个门店每天一张销售出库单。
                List<MtFoodconsumitem> items = mtFoodconsumMapper.dataforSellOut(mtFoodconsum);
                createSellOut(items);

                //3、	菜品消耗明细表中的菜品数据生成产品入库单，按日、按门店汇总生成，每个门店每天一张产品入库单。
                createProductWhin(items);

                bizTimeStart = DateUtils.addDay(bizTimeStart, 1);
                shop.setWhoutAsyndate(bizTimeStart);
                mtShopMapper.updateMtShop(shop);
            }

        }
    }

    private void createProductWhin(List<MtFoodconsumitem> items) {
        //组装入库单
        /*Whinform form = new Whinform();
        form.setCreatedate(DateUtils.getNowDate());
        form.setGuid(IdUtils.fastSimpleUUID());
        form.setDepartmentid(pb.getDepartid());
        form.setStorermguid(pb.getSrguid());
        form.setBusinesscode(pb.getCode());
        form.setFoguid(pb.getGuid());
        form.setOperatorid(user.getGuid());
        form.setOrgguid(pb.getOrgid());
        form.setOrgname(pb.getOrgname());
        form.setWhintype(9);
        form.setSupplierId(Long.valueOf(pb.getSupplierid()));
        form.setSupplierName(pb.getSupplier());
        form.setCurrency(pb.getCurrency());
        form.setSettlOrgId(pb.getOrgid());
        form.setSettlOrgName(pb.getOrgname());
        form.setFormno(businesscodeService.getCode("4"));
        for (Whinformitem item : items) {
            //获取库间
            Storehouseroom house = storehouseroomMapper.selectStorehouseroomById(item.getShrguid());

            Purchasebillitem pbitem = purchasebillitemMapper.selectPurchasebillitemById(item.getApplyitemid());

            Salesspecification spe = salesspecificationMapper.selectSalesspecificationById(pbitem.getSpguid());
            item.setGuid(IdUtils.fastSimpleUUID());
            item.setSpguid(pbitem.getSpguid());
            item.setSrguid(form.getStorermguid());
            item.setProductguid(pbitem.getProductguid());
            item.setOrgguid(form.getOrgguid());
            item.setOrgname(form.getOrgname());
            item.setBweight(item.getWeight());
            if (spe.getStockunitid() == pbitem.getStockunitid()) {//判断是否以库存单位下单
                item.setStockunitid(pbitem.getStockunitid());
                item.setStockunit(pbitem.getStockunit());
            } else {
                item.setStockunitid(spe.getStockunitid());
                item.setStockunit(spe.getStockunit());
                BigDecimal newWeight = qtyToWeight(pbitem.getStockunitid(), spe.getStockunitid(), pbitem.getSpguid(), item.getWeight());
                item.setWeight(newWeight);
            }
            BigDecimal priceRecover = item.getBweight().multiply(pbitem.getPrice()).divide(item.getWeight(),6, BigDecimal.ROUND_DOWN);
            item.setPrice(priceRecover);
//            BigDecimal amount = item.getPrice().multiply(item.getWeight());
            item.setAmount(pbitem.getAmount());
        }
        return form;*/
    }

   /* private void createOut(List<MtFoodconsumgoodsitem> items) {
        MtFoodconsumgoodsitem mtFoodconsumitem = items.get(0);
        String guid = IdUtils.fastSimpleUUID();
        Organization organization = organizationMapper.selectOrganizationByAutoId(mtFoodconsumitem.getOrgId());
        Customer customer = customerMapper.selectCustomerByNewId(mtFoodconsumitem.getCustomerId());
        String orgguid = organization.getGuid();

        Whoutform whoutform = new Whoutform();
        whoutform.setGuid(guid);
        whoutform.setIsCopytoKD(1);
        whoutform.setDepartmentid(mtFoodconsumitem.getDepartmentguid());
        whoutform.setOuttype(2);
        whoutform.setSrguid(mtFoodconsumitem.getStoreroomguid());
        whoutform.setSettlOrgId(orgguid);
        whoutform.setSettlOrgName(mtFoodconsumitem.getOrgName());
        whoutform.setRevCustId(customer.getGuid());
        whoutform.setRevCustName(mtFoodconsumitem.getCustomerName());
        whoutform.setCurrency(1);
        whoutform.setOuttime(new Date());
        whoutform.setOrgguid(orgguid);
        whoutform.setOrgname(mtFoodconsumitem.getOrgName());
        whoutform.setWhoutcode(codeService.getCode("7"));
        whoutform.setCreatetime(DateUtils.getNowDate());
        whoutformMapper.insertWhoutform(whoutform);

        for (MtFoodconsumitem item : items) {
            // 保存明细
            BigDecimal weight = new BigDecimal(0);
            Whoutformitem whoutformitem = new Whoutformitem();
            whoutformitem.setGuid(IdUtils.fastSimpleUUID());
            whoutformitem.setSrguid(item.getStoreroomguid());
            whoutformitem.setWhoutid(guid);
            whoutformitem.setOrgguid(orgguid);
            whoutformitem.setOrgname(item.getOrgName());
            whoutformitem.setSpguid(item.getSpguid());
            whoutformitem.setSpename(item.getSpname());
            whoutformitem.setPrice(item.getErpPrice());
            whoutformitem.setStockunitid(item.getStockunitid());
            whoutformitem.setStockunit(item.getStockunitname());
            whoutformitem.setWeight(item.getErpWeight());
            whoutformitem.setCreateTime(DateUtils.getNowDate());
            whoutformitem.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
            whoutformitemMapper.insertWhoutformitem(whoutformitem);
            weight = weight.add(whoutformitem.getWeight());
            whoutform.setWeight(weight);
            whoutformMapper.updateWhoutform(whoutform);
        }
    }*/

    private void createSellOut(List<MtFoodconsumitem> items) {
        MtFoodconsumitem mtFoodconsumitem = items.get(0);
        String guid = IdUtils.fastSimpleUUID();
        Organization organization = organizationMapper.selectOrganizationByAutoId(mtFoodconsumitem.getOrgId());
        Customer customer = customerMapper.selectCustomerByNewId(mtFoodconsumitem.getCustomerId());
        String orgguid = organization.getGuid();

        Whoutform whoutform = new Whoutform();
        whoutform.setGuid(guid);
        whoutform.setIsCopytoKD(1);
        whoutform.setDepartmentid(mtFoodconsumitem.getDepartmentguid());
        whoutform.setOuttype(2);
        whoutform.setSrguid(mtFoodconsumitem.getStoreroomguid());
        whoutform.setSettlOrgId(orgguid);
        whoutform.setSettlOrgName(mtFoodconsumitem.getOrgName());
        whoutform.setRevCustId(customer.getGuid());
        whoutform.setRevCustName(mtFoodconsumitem.getCustomerName());
        whoutform.setCurrency(1);
        whoutform.setOuttime(new Date());
        whoutform.setOrgguid(orgguid);
        whoutform.setOrgname(mtFoodconsumitem.getOrgName());
        whoutform.setWhoutcode(codeService.getCode("7"));
        whoutform.setCreatetime(DateUtils.getNowDate());
        whoutformMapper.insertWhoutform(whoutform);

        for (MtFoodconsumitem item : items) {
            // 保存明细
            BigDecimal weight = new BigDecimal(0);
            Whoutformitem whoutformitem = new Whoutformitem();
            whoutformitem.setGuid(IdUtils.fastSimpleUUID());
            whoutformitem.setSrguid(item.getStoreroomguid());
            whoutformitem.setWhoutid(guid);
            whoutformitem.setOrgguid(orgguid);
            whoutformitem.setOrgname(item.getOrgName());
            whoutformitem.setSpguid(item.getSpguid());
            whoutformitem.setSpename(item.getSpname());
            whoutformitem.setPrice(item.getErpPrice());
            whoutformitem.setStockunitid(item.getStockunitid());
            whoutformitem.setStockunit(item.getStockunitname());
            whoutformitem.setWeight(item.getErpWeight());
            whoutformitem.setCreateTime(DateUtils.getNowDate());
            whoutformitem.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
            whoutformitemMapper.insertWhoutformitem(whoutformitem);
            weight = weight.add(whoutformitem.getWeight());
            whoutform.setWeight(weight);
            whoutformMapper.updateWhoutform(whoutform);
        }
    }

    private void createProduceReport(Date bizTimeStart, Date bizTimeEnd, List<MtFoodconsumgoodsitem> goodsItems) {
        for (MtFoodconsumgoodsitem item : goodsItems) {
            Organization organization = organizationMapper.selectOrganizationByAutoId(item.getOrgId());
            Department department = departmentMapper.selectDepartmentById(item.getDepartmentguid());
            String orgguid = organization.getGuid();

            Producereport producereport = new Producereport();
            producereport.setOrgguid(orgguid);
            producereport.setOrgname(item.getOrgName());
            producereport.setDepartid(item.getDepartmentguid());
            producereport.setDepartname(department.getName());
            producereport.setSrguid(item.getStoreroomguid());
            producereport.setSrname(item.getStoreroomname());
            producereport.setIntype(1);
//                    producereport.setOrderdate(item.getBizTime());
            producereport.setStarttime(bizTimeStart);
            producereport.setEndtime(bizTimeEnd);
            producereport.setCreattime(DateUtils.getNowDate());
            producereportMapper.insertProducereport(producereport);

            Producereportitem ppItem = new Producereportitem();
            ppItem.setProducereportid(producereport.getId());
            ppItem.setDepartid(item.getDepartmentguid());
            ppItem.setDepartname(department.getName());
            ppItem.setSrguid(item.getStoreroomguid());
            ppItem.setSrname(item.getStoreroomname());
            ppItem.setShrguid(item.getStorehouseguid());
            ppItem.setShrname(item.getStorehousename());
            ppItem.setOutproductid(item.getProductguid());
            ppItem.setOutproduct(item.getProductname());
            ppItem.setOutspecid(item.getSpguid());
            ppItem.setOutspecname(item.getSpname());
            ppItem.setOutstockunitid(item.getStockunitid());
            ppItem.setOutstockunit(item.getStockunitname());
            ppItem.setOutweight(item.getErpWeight());
            ppItem.setCospguid(item.getSpguid());
            ppItem.setCospname(item.getSpname());
            producereportitemMapper.insertProducereportitem(ppItem);
        }
    }
}
